package com.jwdf.uda.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.ActivitySearchInvitationBinding;
import com.jwdf.uda.event.InvitationEvent;
import com.jwdf.uda.event.SearchInputEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.HasBeenInvitedUserListAction;
import com.jwdf.uda.http.action.InviteAnswerAction;
import com.jwdf.uda.ui.fragment.search.SearchInvitationFragment;
import com.jwdf.uda.ui.fragment.search.SearchInvitationResultsFragment;
import com.jwdf.uda.utils.DisplayUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.UdaUtils;
import com.jwdf.uda.view.gallery.ClassifyGallery;
import com.jwdf.uda.view.gallery.ClassifyItemClickListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/5/19.
 */
public class SearchInvitationActivity extends AbsActivity {

    private int mQuestionId;
    private  ClassifyGallery invitedThumb;
    public List<PbBean.PbUserSimple> likeInfos=new ArrayList<>();
    private int mUserCount;
    public static void start(Context context, int  questionId) {
        Intent intent = new Intent(context, SearchInvitationActivity.class);
        intent.putExtra("questionId", questionId);
        context.startActivity(intent);
    }

    private ActivitySearchInvitationBinding mDataBinding;
    private TextWatcher mTextChangeListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //mDataBinding.searchEdit.setSelection(s.length());
        }

        @Override
        public void afterTextChanged(Editable s) {
            if(TextUtils.isEmpty(s)) {
                showRecordFragment();
            }
            mDataBinding.ivClearInput.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
        }
    };
    private TextView.OnEditorActionListener mActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if(actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                String content = mDataBinding.searchEdit.getText().toString().trim();
                if(!TextUtils.isEmpty(content)) {
                    UdaUtils.hideInputMethod(v.getContext(), v);
                    mDataBinding.ivClearInput.setVisibility(View.VISIBLE);
                    showResultFragment(content);
                }
                return true;
            }
            return false;
        }
    };

    @Override
    protected boolean fullScreenMode() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        likeInfos.clear();
        mQuestionId=getIntent().getIntExtra("questionId",0);
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_search_invitation);
        ViewStub viewStub=(ViewStub)findViewById(R.id.placeholder_invited);
        viewStub.inflate();
        invitedThumb=(ClassifyGallery)findViewById(R.id.view_thumb);
        initViews();
    }
    private void initViews() {
        RelativeLayout.LayoutParams flParams = (RelativeLayout.LayoutParams) mDataBinding.searchBarLayout.getLayoutParams();
        flParams.height += DisplayUtils.getStatusBarHeight(this);
        mDataBinding.searchBarLayout.setLayoutParams(flParams);
        mDataBinding.searchBarLayout.setPadding(DisplayUtils.dipToPix(this,10), DisplayUtils.getStatusBarHeight(this), DisplayUtils.dipToPix(this,10), 0);

        mDataBinding.searchEdit.setHint(getString(R.string.search_invitation_hint));
        mDataBinding.searchEdit.setOnEditorActionListener(mActionListener);
        mDataBinding.searchEdit.addTextChangedListener(mTextChangeListener);
        mDataBinding.ivClearInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDataBinding.searchEdit.setText("");
            }
        });
//        initUserSimple(true);
        showRecordFragment();
        updateHasBeenInviteUserList(true);
}

    public void onEvent(InvitationEvent event){
        switch (event.getEvent()){
            case InvitationEvent.INVITATION_ANSWER:
                requestAnswer(event.getUserSimple());
                break;
        }

    }

    private void initUserSimple(boolean isRefresh){
        if(likeInfos.size()!=0){
            invitedThumb.setVisibility(View.VISIBLE);
            invitedThumb.bindView(isRefresh,likeInfos, new ClassifyItemClickListener() {
                @Override
                public void onItemClick(String userId, String style, boolean isDesigner) {

                }

                @Override
                public void onItemClick(Context context, String userId, boolean isDesigner) {
                    UserInfoActivity.start(context, userId, isDesigner);
                }
            });

        }else {
            invitedThumb.setVisibility(View.VISIBLE);
            invitedThumb.bindTextView();
        }
        invitedThumb.setClassifyTouchMoveListener(new ClassifyGallery.OnClassifyTouchMoveListenerListener() {
            @Override
            public void onTouchMove() {
                if(mUserCount>likeInfos.size()) {
                    Log.i("----",likeInfos.size()+"");
                    updateHasBeenInviteUserList(false);
                }
            }
        });
//        List<PbBean.PbUserSimple> userSimples=likeInfos;
//        Collections.reverse(likeInfos);
//        ClassifyGallery invitedThumb=(ClassifyGallery) mDataBinding.placeholderInvited.getViewStub().inflate();


//            mDataBinding.viewThumb.bindView(0,likeInfos, new ClassifyItemClickListener() {
//            @Override
//            public void onItemClick(String userId, String style, boolean isDesigner) {
//
//            }
//
//            @Override
//            public void onItemClick(String userId, boolean isDesigner) {
//                UserInfoActivity.start(getApplicationContext(), userId, isDesigner);
//            }
//        });
    }


    private void showRecordFragment() {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_list_container, SearchInvitationFragment.instance("",mQuestionId), null).commitAllowingStateLoss();
    }
    @Override
    protected void onStart() {
        super.onStart();
        EventBusUtil.registerEvent(this);
    }
    @Override
    protected void onStop() {
        super.onStop();
        EventBusUtil.unregisterEvent(this);
    }
    public void onEvent(SearchInputEvent event) {
        mDataBinding.searchEdit.setText(event.content);
        showResultFragment(event.content);
    }
    private void showResultFragment(String content) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_list_container, SearchInvitationResultsFragment.instance(content, PbBean.PbSignInviteUserListType.INVITE_USER_LIST_TYPE_FOLLOW,mQuestionId), null).commitAllowingStateLoss();
    }
    public void onCancel(View view) {
        finish();
    }

    protected void requestAnswer(final PbBean.PbUserSimple userSimple) {
//        showProgressDialog();
        onNewRequestCall(InviteAnswerAction.newInstance(getApplicationContext(),mQuestionId,userSimple.getUserId())
                .request(new AHttpService.IResCallback<PbBean.PbResQuestionInviteAnswer>() {
                    @Override
                    public void onCallback(int resultCode, Response<PbBean.PbResQuestionInviteAnswer> response, PbBean.PbBaseServerInfo
                            baseServerInfo) {
//                        closeProgressDialog();
                        if(HttpHelper.showError(getApplicationContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                            return;
                        }else {
                            initUserList(userSimple);
//                            updateHasBeenInviteUserList(true);
                            EventBusUtil.post(new InvitationEvent(InvitationEvent.INVITATION_ADD ,userSimple));
                        }

                    }
                }));
    }

    protected void updateHasBeenInviteUserList(final boolean refresh){
//        if(!refresh) {
        closeProgressDialog();
            showProgressDialog();
//        }
        int offset = refresh ? 0 :likeInfos.size();
        onNewRequestCall(HasBeenInvitedUserListAction.newInstance(getApplicationContext(),mQuestionId,offset)
        .request(new AHttpService.IResCallback<PbBean.PbResQuestionHasBeenInvitedUserList>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionHasBeenInvitedUserList> response, PbBean.PbBaseServerInfo baseServerInfo) {

                if(HttpHelper.showError(getApplicationContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                    closeProgressDialog();
                    return;
                }else {
//                    likeInfos=response.body().getUserListList();
//                    Collections.reverse(likeInfos);

                    doSuccessResponse(refresh , response.body());
                }
            }
        }));
    }


    private void doSuccessResponse(boolean refresh, PbBean.PbResQuestionHasBeenInvitedUserList body) {
        if (body != null) {
            if (body.getUserListList().isEmpty()) {
                initUserSimple(refresh);
                closeProgressDialog();
            } else {
                mUserCount=body.getUserCount();
                if (refresh) {
                    likeInfos.clear();
                    for (int i=0;i<body.getUserListList().size();i++){
                        likeInfos.add(body.getUserList(i));
                    }
                    initUserSimple(refresh);
                    closeProgressDialog();
                } else {
                    for (int i=0;i<body.getUserListList().size();i++){
                        likeInfos.add(body.getUserList(i));
                    }
                    initUserSimple(refresh);
                    closeProgressDialog();
                }
            }

        }
    }

    private void initUserList(PbBean.PbUserSimple userSimple){
        Collections.reverse(likeInfos);
        likeInfos.add(userSimple);
        Collections.reverse(likeInfos);
        initUserSimple(true);
    }

}

